package com.zhao.Others;

import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 1.保存图片到服务器，返回访问路径
 * 2.判断图片是否存在
 */
public class FileOperationObject {

    //获取项目classes/static的地址
    public static String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath()+"/";

    //判断图片是否存在
    public static boolean isExists(String visitPath){
        String savePath = staticPath + visitPath;
        System.out.println(savePath);
        File saveFile = new File(savePath);
        if(saveFile.exists()){
            System.out.println("exist "+visitPath);
            return true;
        }
        System.out.println("do not exist "+visitPath);
        return false;
    }

    private static int mutex = 0;

    //保存图片到服务器
    public static String savePicture(MultipartFile file,String directoryName,String universityID,String userID){

        try{
            Thread.sleep(1000);
        }catch (Exception e){
            System.out.println("sleep 1s");
            e.printStackTrace();
        }

        String fileName = file.getOriginalFilename();  //获取文件名
        System.out.println(fileName);
        String houzhui = fileName.substring(fileName.lastIndexOf("."),fileName.length());
        //System.out.println("后缀"+houzhui);
        String newFileName = GenerateObject.getNameOfPicture(directoryName,universityID,userID)+houzhui;

        // 图片存储目录及图片名称
        String url_path = directoryName + "/"  + newFileName;
        //图片保存路径
        String savePath = staticPath + url_path;

        // 访问路径=静态资源路径+文件目录路径
        String visitPath = url_path;
        System.out.println(visitPath);

        File saveFile = new File(savePath);
        if (!saveFile.exists()){
            saveFile.mkdirs();
        }else{
            System.out.println("图片已经存在");
            return visitPath;
        }
        try {
            file.transferTo(saveFile);  //将临时存储的文件移动到真实存储路径下
            System.out.println("图片保存地址："+savePath);
            System.out.println("图片访问url："+visitPath);
            return visitPath;
        } catch (IOException e) {
            System.out.println("here!!!");
            e.printStackTrace();
            return null;
        }

    }

    public static void main(String[] args) {
        System.out.println(isExists("supervisepicture/supervise.jpg"));
    }
}
